import LinedList from "./实现单向链表LinkedList";

class CircularLinkedList<T> extends LinedList<T> {
  // 重写新增，在旧代码后面，让新节点next指向tail
  append(item: T): void {
    super.append(item);
    this.tail!.next = this.head;
  }

  // 重写遍历，在旧的遍历上再多加一个标识证明是循环列表
  traverse(): string {
      super.traverse();
      return `${super.traverse()}->${this.tail?.next?.data}`;
  }

  // 重新插入，插入到最前面和最外面，tail的next指向也要修改
  insert(position: number, element: T): T | null{
    const res= super.insert(position, element)
    if(res && (position === this.size - 1  || position === 0)){
        this.tail!.next = this.head;
    }
    return res
  }

  // 删除节点，删除的节点是第一个或者最后一个节点，tail的next指向也要修改
  removeAt(position: number): T | undefined {
      const res = super.removeAt(position)
      if(res && this.tail && (position === this.size  || position === 0)){        
          this.tail!.next = this.head;
      }    
      return res
  }
}

const circlarLinkedList1 = new CircularLinkedList();

circlarLinkedList1.append("a");
circlarLinkedList1.append("b");
circlarLinkedList1.append("c");
circlarLinkedList1.append("d");
circlarLinkedList1.append("e");
circlarLinkedList1.append("f");
console.log(circlarLinkedList1.traverse());

circlarLinkedList1.insert(0, "0a");
circlarLinkedList1.insert(2, "2c");
circlarLinkedList1.insert(8, "6f");
console.log(circlarLinkedList1.traverse());



circlarLinkedList1.removeAt(8);
circlarLinkedList1.removeAt(0);
circlarLinkedList1.removeAt(1);
console.log(circlarLinkedList1.traverse());


console.log(circlarLinkedList1.indexOf('a'));
console.log(circlarLinkedList1.indexOf('f'));
console.log(circlarLinkedList1.indexOf('ff'));
